﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Threading.Tasks;
using System.Xml.Serialization;
using theTVDB.Xml;

//[assembly: CLSCompliant(true)]

namespace theTVDB
{
    public class TVDB
    {
        private string apiKey;
        private const string FIXED_MIRROR = "http://thetvdb.com/";
        private string addrPrefixWithApiKey, addrPrefixWithoutApiKey;

        public TVDB(string apiKey)
        {
            this.apiKey = apiKey;
            this.addrPrefixWithApiKey = FIXED_MIRROR + "api/" + apiKey + "/";
            this.addrPrefixWithoutApiKey = FIXED_MIRROR + "api/";
        }

        private static async Task<T> DoStaticQuery<T>(string xmlPath) where T : class
        {
            HttpWebRequest request = HttpWebRequest.CreateHttp(xmlPath);
            WebResponse response = await Task.Factory.FromAsync<WebResponse>(request.BeginGetResponse, request.EndGetResponse, null);

            using (var responseStream = response.GetResponseStream())
            {
                XmlSerializer serializer = new XmlSerializer(typeof(T));
                return serializer.Deserialize(responseStream) as T;
            }
        }

        private static Dictionary<Type, string> addrSuffixMap = new Dictionary<Type, string>()
        {
            {typeof(Mirrors), "mirrors.xml"},
            {typeof(Languages), "languages.xml"}
        };

        public async Task<T> RetrieveStaticData<T, U>() where T : class, IXmlCollectionWrapper<U>
        {
            string suffix;
            try
            {
                suffix = addrSuffixMap[typeof(T)];
            }
            catch (KeyNotFoundException knfEx)
            {
                throw new NotImplementedException(
                    String.Format("Static retrieval for {0} is not implemented", typeof(T)),
                    knfEx);
            }

            return await DoStaticQuery<T>(this.addrPrefixWithApiKey + suffix);
        }
    }
}